package com.lh.glorypavilion.service.trade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.lh.glorypavilion.dto.CourseDto;
import com.lh.glorypavilion.dto.MemberDto;
import com.lh.glorypavilion.exception.glorypavilionEx;
import com.lh.glorypavilion.result.ResultCode;
import com.lh.glorypavilion.service.trade.entity.Order;
import com.lh.glorypavilion.service.trade.entity.PayLog;
import com.lh.glorypavilion.service.trade.feign.EduCourseService;
import com.lh.glorypavilion.service.trade.feign.UcenterMemberService;
import com.lh.glorypavilion.service.trade.mapper.OrderMapper;
import com.lh.glorypavilion.service.trade.mapper.PayLogMapper;
import com.lh.glorypavilion.service.trade.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.glorypavilion.service.trade.util.OrderNoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author lhui
 * @since 2020-10-23
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private EduCourseService eduCourseService;

    @Autowired
    private UcenterMemberService ucenterMemberService;

    @Autowired
    private PayLogMapper payLogMapper;

    @Override
    public String saveOrder(String courseId, String memberid) {
        //查询当前用户是否已有当前课程的订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("member_id", memberid);
        Order orderExist = baseMapper.selectOne(queryWrapper);
        if(orderExist != null){
            return orderExist.getId();//如果订单已存在，则直接返回订单id
        }

        //查询课程信息
        CourseDto courseDto = eduCourseService.getCourseDtoById(courseId);
        if(courseDto == null){
            throw new glorypavilionEx(ResultCode.PARAM_ERROR);
        }

        //查询用户信息
        MemberDto memberDto = ucenterMemberService.getMemberDtoByMemberId(memberid);
        if(memberDto == null){
            throw new glorypavilionEx(ResultCode.PARAM_ERROR);
        }

        //创建订单
        Order order = new Order();
        order.setOrderNo(OrderNoUtils.getOrderNo()); //订单号

        order.setCourseId(courseId);
        order.setCourseTitle(courseDto.getTitle());
        order.setCourseCover(courseDto.getCover());
        order.setTeacherName(courseDto.getTeacherName());
        order.setTotalFee(courseDto.getPrice().multiply(new BigDecimal(100)));//单位：分

        order.setMemberId(memberid);
        order.setMobile(memberDto.getMobile());
        order.setNickname(memberDto.getNickname());

        order.setStatus(0);//未支付
        order.setPayType(1); //微信支付

        baseMapper.insert(order);
        return order.getId();
    }

    @Override
    public Order getByOrderId(String orderId, String memberid) {

        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("id",orderId).eq("member_id",memberid);
        return baseMapper.selectOne(orderQueryWrapper);
    }

    @Override
    public Boolean isBuyByCourseId(String courseId, String memberid) {

        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper
                .eq("course_id",courseId)
                .eq("member_id",memberid)
                .eq("status",1);
        Integer integer = baseMapper.selectCount(wrapper);
        return integer.intValue()>0;
    }

    @Override
    public List<Order> selectByMemberId(String memberid) {

        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        orderQueryWrapper.orderByDesc("gmt_create").eq("member_id",memberid);

        return baseMapper.selectList(orderQueryWrapper);
    }

    @Override
    public boolean removeById(String orderId, String memberid) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        orderQueryWrapper.eq("id",orderId).eq("member_id",memberid);
        return this.remove(orderQueryWrapper);
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_no",orderNo);
        return baseMapper.selectOne(orderQueryWrapper);
    }

    @Override
    public void updateOrderStatus(Map<String, String> notifyMap) {
        String out_trade_no = notifyMap.get("out_trade_no");
        Order order = this.getOrderByOrderNo(out_trade_no);
        order.setStatus(1);//支付成功
        baseMapper.updateById(order);

        //记录支付日志
        //记录支付日志
        PayLog payLog = new PayLog();
        payLog.setOrderNo(out_trade_no);
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型：微信支付
        payLog.setTotalFee(Long.parseLong(notifyMap.get("total_fee")));
        payLog.setTradeState(notifyMap.get("result_code"));
        payLog.setTransactionId(notifyMap.get("transaction_id"));
        payLog.setAttr(new Gson().toJson(notifyMap));
        payLogMapper.insert(payLog);

        //更新课程销量
        eduCourseService.updateBuyCountById(order.getCourseId());

    }

    /**
     * 查询支付结果
     * @param orderNo
     * @return true:已支付，false 未支付
     */
    @Override
    public boolean queryPayStatus(String orderNo) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_no",orderNo);
        Order order = baseMapper.selectOne(orderQueryWrapper);
        return order.getStatus()==1;
    }
}
